import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import Details from "../detail.vue";
import {
  getInventoryListApi,
  createInventoryApi,
  updateInventoryApi,
  delInventoryApi,
  getInventoryShowApi
} from "@/api/inventoryApi";
export function useInventory() {
  const form = reactive({
    page: 1,
    perPage: 10,
    status: null,
    orderType: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const indexMethod = (index: number) => {
    return index + 1;
  };
  const columns: TableColumnList = [
    {
      label: "ID",
      type: "index",
      index: indexMethod
    },
    {
      label: "订单号",
      prop: "orderNum",
      minWidth: 140
    },
    {
      label: "订单类型",
      prop: "orderTypeStr"
    },
    {
      label: "公司简称",
      prop: "corp.shortName"
    },
    {
      label: "用户",
      prop: "user.name"
    },
    {
      label: "存货开始日期",
      prop: "storageDate"
    },
    {
      label: "存货结束日期",
      prop: "storageEndDate"
    },
    {
      label: "发货目的地",
      prop: "goodsDest"
    },
    {
      label: "存货备注",
      prop: "remarks"
    },
    {
      label: "状态",
      prop: "statusStr"
    },
    {
      label: "创建时间",
      prop: "createdAt",
      minWidth: 130
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      minWidth: 140
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getInventoryListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = 1;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getInventoryListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = result.result.current_page;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getInventoryListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.per_page;
    pagination.currentPage = result.current_page;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    form.orderType = null;
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
    console.log(row);
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增"
      };
    } else {
      const { result } = await getInventoryShowApi({ InventoryId: 0 });
      formInline.value = {
        title: "修改",
        name: result?.name ?? ""
      };
    }
    addDialog({
      title: `${title}存货订单`,
      props: {
        formInline: formInline
      },
      width: "44%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了存货订单`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              createInventoryApi(curData)
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateInventoryApi(curData)
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();
  });

  function handleDelete(row) {
    delInventoryApi({ storageOrderId: row.storageOrderId }).then(() => {
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  function confirmStatus(value) {
    alert("审核通过" + value);
  }
  function refusedStatus(value) {
    alert("审核拒绝" + value);
  }
  function onDetail(row) {
    getInventoryShowApi({ storageOrderId: row.storageOrderId }).then(res => {
      addDialog({
        top: "5vh",
        width: "49%",
        hideFooter: true,
        contentRenderer: () => h(Details),
        props: {
          info: [res.result]
        }
      });
    });
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
    confirmStatus,
    refusedStatus,
    onDetail
  };
}
